import { useDispatch, useSelector } from 'react-redux'
import classNames from 'classnames'
import { clearCompletedTodo } from '../../store/actions/todo'
import { changeActive } from '../../store/actions/filter'

export default function TodoFooter() {
  const dispatch = useDispatch()
  const todo = useSelector((state) => state.todo)
  const completedLength = todo.filter((item) => item.done).length
  const leftLength = todo.filter((item) => !item.done).length
  const handleClearDoned = () => dispatch(clearCompletedTodo())
  const { list, active } = useSelector((state) => state.filter)
  // !#0 在这儿触发的
  // 平行这儿写的 dispatch 只能接收 action 对象
  // 但是这里的 dispatch 却可以接收函数，为什么呢？
  // 因为这个 dispatch 其实是经过中间件包裹的 dispatch，new dispatch
  const handleClick = (item) => {
    setTimeout(() => {
      dispatch(changeActive(item))
    }, 2000)
  }
  return (
    <footer className='footer'>
      <span className='todo-count'>
        <strong>{leftLength}</strong> item left
      </span>
      <ul className='filters'>
        {list.map((item) => (
          <li key={item} onClick={() => handleClick(item)}>
            <a
              className={classNames({
                selected: item === active,
              })}
              href='#/'
            >
              {item.slice(0, 1).toUpperCase() + item.slice(1)}
            </a>
          </li>
        ))}
      </ul>
      {completedLength > 0 && (
        <button onClick={handleClearDoned} className='clear-completed'>
          Clear completed
        </button>
      )}
    </footer>
  )
}
